package common.service.base.resolver;

import java.lang.annotation.Annotation;

import javax.servlet.http.HttpServletResponse;

import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.alibaba.fastjson.JSON;

import common.service.base.annotation.MobileResponseBody;
import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName MobileResponseParamResolver
 * @Description Todo
 * @Author lixin
 * @Date 2020/02/10 下午3:24
 * Version 0.0.1
 **/
@Slf4j
public class MobileResponseParamResolver implements HandlerMethodReturnValueHandler{
    @Override
    public boolean supportsReturnType(MethodParameter methodParameter) {
        Annotation[] methodAnnotations =
                methodParameter.getMethodAnnotations();
        for (Annotation methodAnnotation : methodAnnotations) {
            if(MobileResponseBody.class.isInstance(methodAnnotation)){
                return true;
            }
        }
        return false;
    }
    @Override
    public void handleReturnValue(Object o, MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest) throws Exception {
        Annotation[] methodAnnotations =
                methodParameter.getMethodAnnotations();
        for (Annotation methodAnnotation : methodAnnotations) {
            if(MobileResponseBody.class.isInstance(methodAnnotation)){
                modelAndViewContainer.setRequestHandled(true);
                String responseBody = JSON.toJSONString(o);
                log.info("服务端输出："+responseBody);
                HttpServletResponse nativeResponse = nativeWebRequest.getNativeResponse(HttpServletResponse.class);

                nativeResponse.setCharacterEncoding("UTF-8");
                nativeResponse.getWriter()
                        .write(responseBody);
            }
        }
    }

}
